package cn.com.greatwall.flowable.service.mapstruct;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.idm.api.User;
import org.flowable.task.api.TaskInfo;
import org.springframework.stereotype.Component;

import cn.com.greatwall.common.base.BaseMapper;
import cn.com.greatwall.flowable.service.dto.TaskInfoDto;
import lombok.RequiredArgsConstructor;

/**
 * @Author herw
 * @Time 2020-11-24 15:36:40
 * @Version 1.0
 * @Description: TODO(用一句话描述该文件做什么)
 */
@Component
@RequiredArgsConstructor
public class TaskMapper implements BaseMapper<TaskInfoDto, TaskInfo> {
    private final HistoryService historyService;
    private final IdentityService identityService;

    @Override
    public TaskInfo toEntity(TaskInfoDto dto) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public TaskInfoDto toDto(TaskInfo entity) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<TaskInfo> toEntity(List<TaskInfoDto> dtoList) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<TaskInfoDto> toDto(List<TaskInfo> entityList) {
        Map<String, String> processInstanceNames = new HashMap<>(16);
        Set<String> processInstanceIds = new HashSet<>();
        for (TaskInfo task : entityList) {
            if (task.getProcessInstanceId() != null) {
                processInstanceIds.add(task.getProcessInstanceId());
            }
        }
        if (processInstanceIds != null && processInstanceIds.size() > 0) {
            historyService.createHistoricProcessInstanceQuery().processInstanceIds(processInstanceIds).list().forEach(processInstance -> processInstanceNames.put(processInstance.getId(), processInstance.getName()));
        }
        
        List<TaskInfoDto> dtoList = new ArrayList<>();
        for (TaskInfo task : entityList) {
            TaskInfoDto result = new TaskInfoDto(task, processInstanceNames.get(task.getProcessInstanceId()));
            result.setOwnerName(getUserName(task.getOwner()));
            result.setAssigneeName(getUserName(task.getAssignee()));
            dtoList.add(result);
        }
        return dtoList;
    }
    
    /**
     * 获取用户名称
     * @param userId /
     * @return
     */
    private String getUserName(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return null;
        }
        User user = identityService.createUserQuery().userId(userId).singleResult();
        if (user != null) {
            return user.getFirstName();
        }
        return null;
    }
}
